# -*- coding: utf-8 -*-
'''
Created on 15/ott/2009

@author: sax
'''
from django.http import HttpResponse
from django.db import models
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext as _

def export_csv(request, **kwargs):
    from django.contrib.admin.views.main import ChangeList

    from xadmin.unicode import UnicodeWriter
    import csv
    model_admin = kwargs['model_admin']    
    list_display = [el for el in model_admin.list_display if el != 'action_checkbox']
    cl = ChangeList(request, model_admin.model, list_display, (), (), None, (), False, 99999999, (), model_admin)
    response = HttpResponse("", content_type='text/plain')
    name = force_unicode(model_admin.verbose_name_plural)
#    response["Content-type"] = "application/vnd.ms-excel"
#    response["Content-Disposition"] = "attachment; filename=%s.csv" % str(name).replace(" ", "_")
    writer = UnicodeWriter(response, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL)
    writer.writerow(list_display)

    for row in cl.result_list:
        line = []
        for field_name in list_display:
            try:
                f = cl.lookup_opts.get_field(field_name)
            except models.FieldDoesNotExist:
                if callable(field_name):
                    attr = field_name
                    value = attr(row)
                elif hasattr(cl.model_admin, field_name) and \
                   not field_name == '__str__' and not field_name == '__unicode__':
                    attr = getattr(cl.model_admin, field_name)
                    value = attr(row)
                else:
                    attr = getattr(row, field_name)
                    if callable(attr):
                        value = attr()
                    else:
                        value = attr

            else:
                value = getattr(row, f.attname)
            try:
                if value :
                    line.append( force_unicode(value) )
                    #line.append(unicode.encode(unicode(value), 'utf-8'))
                else:
                    line.append("")
            except UnicodeDecodeError, e:
                raise Exception(e)
        writer.writerow(line)

    return response
# pylint: disable-msg=W0612
export_csv.label = _('Export csv') 
export_csv.css = "ui-icon-note"
